package com.uwlaser.http.exception;

import com.uwlaser.webservice.exception.WebServiceCodeErrorException;
import lombok.Data;

/**
 * @Author QZK
 * @Description TODO HTTP异常处理
 * @Date 2022-12-07-09:21
 * @Version 1.0
 */
@Data
public class HttpException extends Exception {

    private static final String type = "Http";

    /**
     * 地址
     */
    private String url;
    /**
     * 请求方式
     */
    private String requestMethod;

    /**
     * 请求参数
     */
    private String params;

    /**
     * 参数类型
     */
    private String paramType;

    /**
     * 描述
     */
    private String describe;

    /**
     * 请求结果
     */
    private String requestResult;

    public HttpException(String message) {
        super(handleMsgLength(message));
    }

    public HttpException(String message, String describe) {
        super(handleMsgLength(message));
        this.describe = describe;
    }

    public HttpException(String url, String requestMethod, String params, String paramType,String describe,String message, String requestResult) {
        super(handleMsgLength(message));
        this.url = url;
        this.requestMethod = requestMethod;
        this.params = params;
        this.paramType = paramType;
        this.describe = describe;
        this.requestResult = requestResult;
    }

    /**
     * 处理异常
     * @return
     */
    public static HttpException handleException(String url, String requestMethod, String params, String paramType,Exception e){
        HttpException te = null;
        if(e instanceof HttpException){
            //统一设置异常数据
            te = (HttpException) e;
            te.setUrl(url); //地址
            te.setRequestMethod(requestMethod); //请求方式
            te.setParams(params); //请求体参数
            te.setParamType(paramType); //参数类型
        } else {
            //其他异常默认按照代码异常和数据异常处理
            te = new HttpCodeErrorException(url,requestMethod,params,paramType,"调用HTTP接口发生异常："+e.getMessage());
        }
        return te;
    }

    /**
     * 处理消息长度
     * @return
     */
    private static String handleMsgLength(String message){
        if(message != null && message.length() > 500){
            message = message.substring(0,500);
        }
        return "【请求外部系统异常】" + message;
    }
}
